package com.zeh.bill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zeh.bill.entity.User;
import com.zeh.bill.entity.Vo.UserQueryVo;
import com.zeh.bill.mapper.UserMapper;
import com.zeh.bill.service.FileService;
import com.zeh.bill.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zeh.bill.untils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zeh
 * @since 2022-07-18
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private FileService fileService;

    /**
     * 根据用户名查询用户信息
     * @param userName
     * @return
     */

    @Override
    public  User  findUserByUserName(String userName){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        return baseMapper.selectOne(queryWrapper);
    }


    /**
     * 分页查询用户信息
     * @param page
     * @param userQueryVo
     * @return
     */
    @Override
    public IPage<User> findUserListByPage(IPage<User> page, UserQueryVo userQueryVo){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(userQueryVo.getDepartmentId()),"department_id",userQueryVo.getDepartmentId())
                    .like(!ObjectUtils.isEmpty(userQueryVo.getUsername()),"username",userQueryVo.getUsername())
                    .like(!ObjectUtils.isEmpty(userQueryVo.getRealName()),"real_name",userQueryVo.getRealName())
                    .like(!ObjectUtils.isEmpty(userQueryVo.getPhone()),"phone",userQueryVo.getPhone());
         return baseMapper.selectPage(page,queryWrapper);


    }


    /**
     * 删除用户信息
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteById(Long id) {
        User user = baseMapper.selectById(id);
        baseMapper.deleteUserRole(id);
        if(baseMapper.deleteById(id)>0){
            if(user != null && !ObjectUtils.isEmpty(user.getAvatar())
            && !user.getAvatar().equals(SystemConstants.DEFAULT_AVATAR)){
                fileService.deleteFile(user.getAvatar());
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveUserRole(Long userId, List<Long> roleIds){
        baseMapper.deleteUserRole(userId);
        return baseMapper.saveUserRole(userId,roleIds)>0;
    }


}
